from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from app01 import models
from app01.utils.form import RecordModelForm
from app01.utils.pagination import Pagination
from app01.utils.tool import IsSignIn
import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.styles import Alignment
import datetime
from app01.utils.tool import DateTool, TimePeriod


def record_list(request):
    """签到记录"""

    # 早期代码
    # # 构造搜索
    # data_dict = {}
    # search_data = request.GET.get('q', "")
    # if search_data:
    #     # 根据搜索条件去数据库获取
    #     data_dict["signin_time__contains"] = search_data
    #
    #     # data_dict["user_info__contains"] = search_data
    #
    #     data_dict["ip__contains"] = search_data
    #
    #     data_dict["is_face__contains"] = search_data
    #
    # queryset_t = models.Record.objects.filter(**data_dict)
    # queryset_u = models.Record.objects.filter(**data_dict)
    # queryset_i = models.Record.objects.filter(**data_dict)
    # queryset_f = models.Record.objects.filter(**data_dict)
    # queryset_a = queryset_t.union(queryset_u)
    # queryset_b = queryset_i.union(queryset_f)
    # queryset = queryset_a.union(queryset_b)
    # # 实例化分页对象
    # page_object = Pagination(request, queryset)

    from django.db.models import Q

    search_data = request.GET.get('q', "")

    search_data_gender = search_data
    search_data_face = search_data

    if search_data == "男":
        search_data_gender = 1
    elif search_data == "女":
        search_data_gender = 2
    elif search_data == "是":
        search_data_face = 0
    elif search_data == "否":
        search_data_face = 1

    queryset = models.Record.objects.all().order_by('-id')

    if search_data:
        queryset = queryset.filter(
            Q(signin_time__contains=search_data) |
            Q(user_info__name__contains=search_data) |
            Q(user_info__sid__contains=search_data) |
            Q(user_info__gender__contains=search_data_gender) |
            Q(user_info__depart__title__contains=search_data) |
            Q(ip__contains=search_data) |
            Q(is_face__contains=search_data_face)
        )

    page_object = Pagination(request, queryset)

    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html(),  # 生成页码
        "search_data": search_data,
    }
    if request.session.get("info")["level"] == 0:
        return render(request, 'u_record_list.html', context)
    return render(request, 'record_list.html', context)


def record_add(request):
    """新增签到"""
    if request.method == 'GET':
        current_time = datetime.datetime.now()
        new_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
        # 获取访问用户的IP地址
        ip = request.META.get('REMOTE_ADDR')
        form = RecordModelForm(initial={'signin_time': new_time, 'ip': ip})
        return render(request, 'record_add.html', {"form": form})

    # 获取用户POST提交过来的数据
    form = RecordModelForm(data=request.POST)
    exists = IsSignIn().get_result(request.POST["user_info"])
    if exists:
        form.add_error("signin_time", "今日已签到")
        return render(request, 'record_add.html', {"form": form})

    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        # 重定向回列表
        return redirect('/record/list/')

    return render(request, 'record_add.html', {"form": form})


def record_edit(request, nid):
    """ 编辑签到 """
    row_object = models.Record.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = RecordModelForm(instance=row_object)
        return render(request, 'record_edit.html', {'form': form})

    # 修改数据时要加上instance属性并用原数据赋值
    # 否则就会只根据用户提供的数据在数据库进行新数据的创建，而不是在原数据的基础上进行修改
    form = RecordModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据，如果想要再用户输入以外增加一点值
        # form.instance.字段名 = 值
        form.save()
        return redirect('/record/list/')
    # 如果数据校验失败就会带着错误信息返回编辑界面
    return render(request, 'record_edit.html', {"form": form})


def record_delete(request):
    """ 删除签到 """
    # 获取ajax发送的ID http://127.0.0.1:8000/user/delete/?nid=1
    uid = request.GET.get('uid')

    # 删除前确认数据是否存在
    exists = models.Record.objects.filter(id=uid).exists()
    if not exists:
        # 如果数据不存在返回错误信息
        return JsonResponse({"status": False, 'error': "删除失败，数据不存在。"})
    # 如果存在进行删除操作
    models.Record.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})


@csrf_exempt
def record_add_day(request):
    """用户每日签到"""
    # 获取ajax发送的type
    type = request.POST.get('type')

    user_info = request.session.get('info')

    nid = user_info["id"]

    # 添加前确认数据是否存在

    exists = IsSignIn().get_result(nid)

    if exists:
        # 如果数据不存在返回错误信息
        return JsonResponse({"status": False, 'error': "签到失败，今日已签到！"})

    # print(exists, type, nid)
    # 如果不存在进行签到操作
    current_time = datetime.datetime.now()
    new_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
    # 获取访问用户的IP地址
    ip = request.META.get('REMOTE_ADDR')
    if type == "noFace":
        form = RecordModelForm(data={'signin_time': new_time, 'ip': ip, 'is_face': 1, 'user_info': nid})
        if form.is_valid():
            # 如果数据合法，保存到数据库
            form.save()
            return JsonResponse({"status": True})
        else:
            # print(form.errors)
            return JsonResponse({"status": False, 'error': "签到失败，数据错误！"})

    return JsonResponse({"status": False, 'error': "签到失败，未完成人脸！(人脸识别功能待完成•ࡇ•)"})


def data_to_excel(request):
    set_time = request.GET.get("time")
    set_time = int(set_time)
    # 查询数据库获取数据，假设获取到的数据存储在records变量中
    records = TimePeriod().get_result(set_time)

    # 创建一个新的Excel文件
    workbook = openpyxl.Workbook()
    worksheet = workbook.active

    # 写入第一行表头
    headers = ['ID', '签到时间', '学号', '姓名', '性别', '所属部门', 'IP地址', '是否人脸']
    for col_num, header in enumerate(headers, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=header)
        cell.alignment = Alignment(horizontal='center')

    # 写入数据
    for row_num, record in enumerate(records, 2):
        worksheet.cell(row=row_num, column=1, value=record.id)
        worksheet.cell(row=row_num, column=2, value=record.signin_time.strftime("%Y{y}%m{m}%d{d} %H:%M").format(y='年', m='月', d='日'))
        worksheet.cell(row=row_num, column=3, value=record.user_info.sid)
        worksheet.cell(row=row_num, column=4, value=record.user_info.name)
        worksheet.cell(row=row_num, column=5, value=record.user_info.get_gender_display())
        worksheet.cell(row=row_num, column=6, value=record.user_info.depart.title)
        worksheet.cell(row=row_num, column=7, value=record.ip)
        worksheet.cell(row=row_num, column=8, value=record.get_is_face_display())

    # 设置列宽
    for col_num in range(1, len(headers) + 1):
        if col_num == 2:
            col_letter = get_column_letter(col_num)
            worksheet.column_dimensions[col_letter].width = 23
            continue

        col_letter = get_column_letter(col_num)
        worksheet.column_dimensions[col_letter].width = 15

    # 创建HttpResponse对象并设置文件头
    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = f'attachment; filename={set_time}day_record.xlsx'

    # 将Excel文件保存到HttpResponse对象中
    workbook.save(response)

    return response
